// 收款核算
<template>
  <div>
    <el-dialog class="con-dialog" :class="isInfo ? 'margin-top-60' : ''" :title="pageType == 'cashPledge' ? '押金返还' : '退款'" z-index="1000" :fullscreen="isInfo ? true : false" :modal="isInfo ? false : true" :visible.sync="dialogShow" width="90%" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-table class="new-table-style bold-scrollbar-table cost-box" :border="true" :data="tableData" align="left">
        <el-table-column align="center" label="序号">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="客户" width="130" prop="customerName"></el-table-column>
        <el-table-column align="left" label="费项名称" width="130" prop="bizTypeName"></el-table-column>
        <el-table-column align="left" label="资产编号" width="130" prop="chargeItemCode"></el-table-column>
        <el-table-column align="center" label="应缴日期" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.paymentDeadline | formatDateTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="计费开始日期" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.cycleStartTime | formatDateTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="计费结束日期" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.cycleEndTime | formatDateTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="总金额" class-name="no-padding" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.amountReceivable | moneyFilterNoUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="未结金额" class-name="no-padding" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.unPaymentAmount | moneyFilterNoUnit }}</span>
          </template> </el-table-column
        >unPaymentAmount
        <el-table-column align="center" label="本次退款金额" class-name="no-padding" min-width="120">
          <template slot-scope="scope">
            <el-input-number :controls="false" :max="0" :disabled="isInfo ? true : false" class="no-border-input" v-model="scope.row.refundAmount" @blur="triggerAmount(scope.row)"  placeholder="请输入"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" class-name="no-padding" min-width="120" v-if="!isInfo">
          <template slot-scope="scope">
            <el-button type="text" class="color-red" @click="deleteFn(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="font-size-17 font-weight-700 padding-top-40 padding-bottom-20">退款信息</div>
      <form-common :filed-list="formList" ref="form" :formObj="formObj"></form-common>

      <div slot="footer" class="dialog-footer" v-if="!isInfo">
        <el-button @click="dialogShow = false" class="el-button-reset">取 消</el-button>
        <el-button type="primary" @click="confirmFn">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { billRefundList } from '../../../assets/form';
  import formCommon from '@g/components/form/formCommon.vue';
  import { apiRefund, apiRefundDetail } from '../../../api/billManage';
  import { apiDepositWorkReturn } from '../../../api/depositManage';
  import { accSubtr, requestTips, askDialog } from '@/common/js/utils.js';
  import $ from 'jquery';
  import { apiCreateAudit } from '@a/index';

  export default {
    name: 'gatherAdjust',

    props: {
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
      checkList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      isInfo: {
        type: Boolean,
        default: false,
      },
      pageType: {
        type: String,
        default: '',
      },
    },

    data() {
      return {
        dialogShow: false,
        formList: billRefundList,
        formObj: {},
        tableData: [],
        accSubtr: accSubtr,
        userInfo: JSON.parse(localStorage.getItem('userInfo')),
      };
    },

    watch: {
      options: {
        deep: true,
        handler(val) {
          this.setSelectOptions();
        },
      },
    },

    methods: {
      init() {
        this.dialogShow = true;
        this.getInfo();
        if (this.isInfo) {
          this.initDomSetting();
          this.banForm();
        }
      },

      async getInfo() {
        let billKeys = this.checkList.map(item => {
          return item.primaryKey;
        });
        let params = {};
        if (this.isInfo) {
          params = { workId: this.$route.query.processWorkId };
        } else {
          params = { billKeys: billKeys };
        }
        let res = await apiRefundDetail(params);
        if (this.isInfo) {
          this.formObj = res;
        }
        this.tableData = res.itemList || [];
        this.tableData.forEach(item => {
          item.billKey = item.primaryKey;
        });

        if (!this.isInfo) {
          this.initFormData();
        }
      },

      initFormData() {
        this.$set(this.formObj, 'applyUser', this.userInfo.key);
        this.$set(this.formObj, 'applyUserName', this.userInfo.nickname);
        this.$set(this.formObj, 'customerInfoKey', this.tableData[0].customerKeys);
        this.$set(this.formObj, 'customerInfoName', this.tableData[0].customerName);
      },

      deleteFn(index) {
        this.tableData.splice(index, 1);
      },

      //退款收款金额<0才能提交
      confirmFn() {
        if (this.tableData.length == 0) {
          this.$message.warning('账单为空！！');
          return;
        }

        let model = this.$refs.form.validateForm(); //基本信息
        if (!model) return;

        // if (model.refundAmount > 0 || model.refundAmount == 0 || !model.refundAmount) {
        //   this.$message.warning('无退款金额！');
        //   return;
        // }

        // let validateMustCost = this.validateMustCost();
        // if (!validateMustCost) {
        //   this.$message.warning('每笔账单退款金额不能为空！！');
        //   return;
        // }

        askDialog('确认提交？', async () => {
          model.itemList = this.tableData;

          let res = this.pageType == 'cashPledge' ? await apiDepositWorkReturn(model) : await apiRefund(model);
          if (res.success) {
            this.submitFn(res.key);
          } else {
            this.$message.error(res.message);
          }
        });
      },

      //提审
      async submitFn(key) {
        let projectKey = localStorage.getItem('projectKey');
        let param = {
          businessKey: key,
          userPrimaryKey: this.userInfo.key,
          projectKey: projectKey,
          type: this.pageType == 'cashPledge' ? '押金返还' : '账单退款',
          typeKey: this.pageType == 'cashPledge' ? 'depositRefund' : 'refund',
        };
        let res = await apiCreateAudit(param);
        requestTips(res, () => {
          this.dialogShow = false;
          this.$emit('confirmBillRefund');
        });
      },

      //校验 计算退款金额
      triggerAmount(row) {
        if (row.refundAmount > row.unPaymentAmount) {
          row.refundAmount = row.unPaymentAmount;
        }
        let price = this.getAllAmount();
        this.formObj = this.$refs.form.returnModel()
        this.$set(this.formObj, 'refundAmount', price);
      },

      //计算收款金额
      getAllAmount() {
        let num = this.tableData.reduce((prev, item) => {
          prev += item.refundAmount || 0;
          return prev;
        }, 0);
        return num || 0;
      },

      //校验合同费用约定的必填
      validateMustCost() {
        for (let i = 0, len = $('.cost-box').find('.el-input__inner').length; i < len; i++) {
          let item = $('.cost-box').find('.el-input__inner')[i];
          if ($(item).val() == '') {
            $(item).css('border', '1px solid red');
            return false;
          } else {
            $(item).css('border', 'none');
          }
        }
        return true;
      },

      //赋值下拉框数据源
      setSelectOptions() {
        this.formList.forEach(ele => {
          if (ele.bindFieldName == 'refundMethod') {
            ele.optionList = this.options.paymentMethodList || [];
          }
        });
      },

      //详情时初始化dom
      initDomSetting() {
        $('.con-dialog .el-dialog__header').hide();
      },

      //禁止form必填 可输入
      banForm() {
        this.formList.forEach(item => {
          item.isRequired = false;
          item.isDisabled = true;
        });
      },
    },

    components: { formCommon },
  };
</script>

<style lang="scss" scoped>
.cost-box {
    ::v-deep .el-input.is-disabled .el-input__inner {
      background-color: #fff;
      border-color: #fff;
      color: #333;
      font-size: 16px;
    }
  }
</style>
